package cn.hit.tianqiao.web.servlet;

import cn.hit.tianqiao.domain.Scene;
import cn.hit.tianqiao.service.SceneService;
import cn.hit.tianqiao.service.impl.SceneServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/scene/*")
public class SceneServlet extends HttpServlet {

    SceneService service = new SceneServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求参数中获取 longitude、latitude 和 distance
        String longitudeStr = req.getParameter("longitude");
        String latitudeStr = req.getParameter("latitude");
        String distanceStr = req.getParameter("distance");
        String rec = req.getParameter("rec");

        // 检查参数是否为 null 或空字符串
        if (longitudeStr == null || longitudeStr.trim().isEmpty() ||
                latitudeStr == null || latitudeStr.trim().isEmpty() ||
                distanceStr == null || distanceStr.trim().isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameters");
            return;
        }

        // 转换参数并查询数据库
        double longitude = Double.parseDouble(longitudeStr);
        double latitude = Double.parseDouble(latitudeStr);
        double distance = Double.parseDouble(distanceStr);

        List<Scene> sceneList = new ArrayList<>();
        if (rec != null) {
            sceneList = service.findRecommendScenes(longitude, latitude, distance);
        } else {
            sceneList = service.findScenesWithinDistance(longitude, latitude, distance);
        }

        // 将结果转换为 JSON 格式并返回
        ObjectMapper mapper = new ObjectMapper();
        String jsonSceneList = mapper.writeValueAsString(sceneList);
        resp.setContentType("application/json");
        resp.getWriter().write(jsonSceneList);
    }
}